<template>
<div>
    <!-- 面包屑组件 -->
    <breadcrumb :navData="navData"></breadcrumb>

    <el-card>
        <!-- 添加按钮 -->
        <el-button type="primary" @click="addDialog=true">主要按钮</el-button>

        <!-- 角色列表 -->
        <el-table border :data="rolesData" style="width: 100%">
            <el-table-column type="expand" >
              <!-- 权限说明 -->
              <template slot-scope="scope" >
                    <el-row class="allStyle" v-for="item1 in scope.row.children" :key="item1.id">
                      <!-- 一级权限 -->
                      <el-col :span="6" style="text-align: center;">
                        <el-tag closable effect="dark" @close="delRoles(scope.row,item1.id)">
                          {{item1.authName}}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18">
                          <el-row class="twoStyle" v-for="item2 in item1.children" :key="item2.id">
                            <!-- 二级权限 -->
                            <el-col :span="6" style="text-align: center;">
                              <el-tag closable type="success" effect="dark" @close="delRoles(scope.row,item2.id)">
                                {{item2.authName}}
                              </el-tag>
                              <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 三级权限 -->
                            <el-col :span="18">
                              <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" effect="dark" @close="delRoles(scope.row,item3.id)">
                                {{item3.authName}}
                              </el-tag>
                            </el-col>
                          </el-row>
                      </el-col>
                    </el-row>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- 编辑 -->
                    <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="editOne(scope.row.id)">编辑</el-button>
                    <!-- 删除 -->
                    <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="delOne(scope.row.id)">删除</el-button>
                    <!-- 分配权限 -->
                    <el-button type="warning" size="mini" icon="el-icon-setting" @click="rolesBtn(scope.row)">
                        分配权限
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加模态框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addDialog"
            >
            <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm('addForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑的模态框 --> 
        <el-dialog
            title="编辑角色"
            :visible.sync="editDialog"
            >
            <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName" ></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc" ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限的模态框 -->
        <el-dialog
          title="分配权限"
          :visible.sync="rolesDialog"
          @close="onSetRightDialogClose"
        >
          <el-tree
            ref="treeRef"
            :data="rolesTree"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="defKeys"
            :props="treeProps">
          </el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="rolesDialog = false">取 消</el-button>
            <el-button type="primary" @click="onAddSureRight()">确 定</el-button>
          </span>
        </el-dialog>
    </el-card>
</div>

</template>

<script>
export default {
  components: {},
  data() {
    return {
      //面包屑数据
      navData: ["权限管理", "角色列表"],
      rolesData: [], //角色列表

      //权限相关
      rolesDialog: false, //分配权限
      rolesTree: [], //权限列表（树状）
      //树形控件属性绑定
      treeProps: {
        //设置label的值来设置树形节点的文本展示
        label: "authName",
        //设置children的值来展示子节点信息
        children: "children"
      },
      //设置树形控件中默认被选中的内容
      defKeys: [],
      rolesId: null,

      //添加的数据
      addDialog: false, //添加的弹框
      //添加的数据
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      addRules: {
        //添加的规则
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ]
      },

      //编辑的数据
      // rolesId: "",
      editDialog: false,
      editForm: {
        //编辑的数据
        roleName: "",
        roleDesc: ""
      },
      editRules: {
        //编辑的规则
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ]
      }
    };
  }, // 组件方法

  methods: {
    //获取角色列表
    async getRoles() {
      let res = await this.$http.get("/roles");
      console.log("roles_list", res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesData = res.data;
    },

    //获取权限列表（树状）
    async getRolesTress() {
      let res = await this.$http.get("rights/tree");
      console.log("roles_list", res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesTree = res.data;
    },
    //点击分配权限按钮
    rolesBtn(row) {
      this.rolesId = row.id;
      //获取所有权限列表(树形);
      this.getRolesTress();
      //默认选中内容
      this.defKeys = [];
      this.getRolesRight(row);
      console.log("defKeys", this.defKeys);
      this.rolesDialog = true;
    },
    //递归获取当前用户所有三级权限id
    getRolesRight(rightList) {
      //判断当前权限是否为三级节点
      // console.log('rightList',rightList);  //同下item,代表每一个权限
      if (!rightList.children) {
        //如果没有children，就是三级节点
        return this.defKeys.push(rightList.id);
      }
      rightList.children.forEach(item => {
        // console.log('item',item);  //同上
        return this.getRolesRight(item);
      });
    },
    //关闭分配权限对话框
    onSetRightDialogClose() {
      //关闭分配权限对话框的时候清空所有选中状态
      this.defKeys = [];
    },

    //点击确定添加权限
    async onAddSureRight() {
      //获取属性控件
      let treeRef = this.$refs.treeRef;
      //获取所有被半选的权限id ==>数组
      // let halfCheckedKeys = treeRef.getHalfCheckedKeys();
      //获取所有选中状态的权限id ==>数组
      // let checkedKeys = treeRef.getCheckedKeys();
      //所有被选择的权限id
      // let keys = halfCheckedKeys.concat(checkedKeys)
      let keys = [...treeRef.getHalfCheckedKeys(), ...treeRef.getCheckedKeys()];
      //把所有被选中的权限id 通过,号分割成字符串
      let rids = keys.join(",");
      let res = await this.$http.post(`roles/${this.rolesId}/rights`, {
        rids: rids
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getRoles();
      this.$message.success(res.meta.msg);
      //关闭对话框
      this.rolesDialog = false;
    },

    //点击确定添加
    submitAddForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.$http.post("/roles", this.addForm);
          console.log("roles_addSure", res);
          if (res.meta.status === 201) {
            this.getRoles();
            this.addDialog = false;
            this.$message.success(res.meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //点击编辑按钮
    async editOne(id) {
      this.editDialog = true;
      this.rolesId = id;
      let res = await this.$http.get("/roles/" + id);
      // console.log("res_edit", res);
      this.editForm = res.data;
    },
    //点击确定编辑
    submitEditForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.$http.put(
            "roles/" + this.rolesId,
            this.editForm
          );
          console.log("editSure", res);
          if (res.meta.status == 200) {
            this.getRoles();
            this.editDialog = false;
            this.$message.success("更新角色成功");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //点击删除角色
    delOne(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let res = await this.$http.delete("roles/" + id);
          console.log("delOne", res);
          if (res.meta.status == 200) {
            this.getRoles();
            this.$message.success(res.meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //点击删除指定权限
    async delRoles(row, rightId) {
      let roleId = row.id;
      let res = await this.$http.delete(`roles/${roleId}/rights/${rightId}`);
      console.log("del_roles", res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      row.children = res.data;
    }
  },

  created() {
    this.getRoles();
    this.getRolesTress();
  }
};
</script> 

<style  lang='scss' scoped>
.el-tag {
  margin: 5px 10px;
}
.allStyle {
  border: 1px solid #eee;
  border-bottom: none;
  margin: 0 20px;
  display: flex;
  align-items: center;
  &:first-child {
    border-bottom: none;
  }
  &:last-child {
    border-bottom: 1px solid #eee;
  }
}
.twoStyle {
  border-left: 1px solid #eee;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  &:last-child {
    border-bottom: none;
  }
}
</style>